# -*- coding: utf-8 -*-
"""
配置数据访问层

负责系统配置相关的数据库操作
"""
from typing import List, Dict, Any, Optional
from .base_repository import BaseRepository


class ConfigRepository(BaseRepository):
    """配置数据访问类"""
    
    def __init__(self):
        super().__init__("system_config")
    
    def get_config_by_key(self, config_key: str) -> Optional[Dict[str, Any]]:
        """根据配置键获取配置"""
        sql = """
            SELECT * FROM system_config 
            WHERE config_key = %s AND status = 1
        """
        result = self.execute_custom_query(sql, [config_key], True)
        return result[0] if result else None
    
    def get_configs_by_group(self, config_group: str) -> List[Dict[str, Any]]:
        """根据配置分组获取配置列表"""
        sql = """
            SELECT * FROM system_config 
            WHERE config_group = %s AND status = 1
            ORDER BY config_key
        """
        return self.execute_custom_query(sql, [config_group], True) or []
    
    def get_all_configs(self) -> List[Dict[str, Any]]:
        """获取所有启用的配置"""
        sql = """
            SELECT * FROM system_config 
            WHERE status = 1
            ORDER BY config_group, config_key
        """
        return self.execute_custom_query(sql, [], True) or []
    
    def update_config_value(self, config_key: str, config_value: str, updated_by: Optional[str] = None) -> bool:
        """更新配置值"""
        update_sql = """
            UPDATE system_config SET 
                config_value = %s,
                updated_time = NOW(),
                updated_by = %s
            WHERE config_key = %s AND status = 1
        """
        
        result = self.execute_custom_query(update_sql, [config_value, updated_by, config_key], False)
        return result is not None
    
    def create_config(self, config_data: Dict[str, Any]) -> Optional[str]:
        """创建新配置"""
        import uuid
        from datetime import datetime
        
        config_id = f"CFG{int(datetime.now().timestamp() * 1000)}"
        
        insert_sql = """
            INSERT INTO system_config (
                config_id, config_key, config_value, config_type,
                config_group, config_desc, is_encrypted, is_system,
                status, created_time, created_by
            ) VALUES (
                %s, %s, %s, %s, %s, %s, %s, %s, 1, NOW(), %s
            )
        """
        
        params = [
            config_id,
            config_data.get('config_key'),
            config_data.get('config_value'),
            config_data.get('config_type', 'string'),
            config_data.get('config_group'),
            config_data.get('config_desc'),
            config_data.get('is_encrypted', 0),
            config_data.get('is_system', 0),
            config_data.get('created_by')
        ]
        
        result = self.execute_custom_query(insert_sql, params, False)
        return config_id if result is not None else None
    
    def delete_config(self, config_key: str) -> bool:
        """删除配置（软删除）"""
        update_sql = """
            UPDATE system_config SET 
                status = 0,
                updated_time = NOW()
            WHERE config_key = %s
        """
        
        result = self.execute_custom_query(update_sql, [config_key], False)
        return result is not None
    
    def batch_update_configs(self, configs: List[Dict[str, Any]], updated_by: Optional[str] = None) -> bool:
        """批量更新配置"""
        try:
            for config in configs:
                config_key = config.get('config_key')
                config_value = config.get('config_value')
                
                if config_key and config_value is not None:
                    self.update_config_value(config_key, str(config_value), updated_by)
            
            return True
        except Exception as e:
            print(f"批量更新配置失败: {e}")
            return False
    
    def get_config_groups(self) -> List[Dict[str, Any]]:
        """获取所有配置分组"""
        sql = """
            SELECT 
                config_group,
                COUNT(*) as config_count,
                GROUP_CONCAT(config_key ORDER BY config_key) as config_keys
            FROM system_config 
            WHERE status = 1
            GROUP BY config_group
            ORDER BY config_group
        """
        return self.execute_custom_query(sql, [], True) or [] 
    def execute_custom_query(self, query: str, params: tuple = None, *args, **kwargs):
        """执行自定义查询"""
        try:
            import mysql.connector
            connection = mysql.connector.connect(**self.db_config)
            cursor = connection.cursor(dictionary=True)
            
            if params:
                cursor.execute(query, params)
            else:
                cursor.execute(query)
            
            result = cursor.fetchall()
            cursor.close()
            connection.close()
            
            return result if result else []
        except Exception as e:
            print(f"查询错误: {e}")
            return []
    
    def execute_query(self, query: str, params: tuple = None, *args, **kwargs):
        """执行查询"""
        return self.execute_custom_query(query, params, *args, **kwargs)
    
    def count_query(self, query: str, params: tuple = None, *args, **kwargs):
        """计数查询"""
        try:
            import mysql.connector
            connection = mysql.connector.connect(**self.db_config)
            cursor = connection.cursor()
            
            if params:
                cursor.execute(query, params)
            else:
                cursor.execute(query)
            
            result = cursor.fetchone()
            cursor.close()
            connection.close()
            
            return result[0] if result else 0
        except Exception as e:
            print(f"计数错误: {e}")
            return 0
